package net.pws.oos.web.dto;

import net.pws.common.beanutils.BeanUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.oos.biz.model.Organization;

import org.apache.commons.lang.StringUtils;

public class OrganizationDto extends Organization {
    
	private static final long serialVersionUID = -8204623801163155965L;

	public static OrganizationDto from(Organization organization) {
        OrganizationDto result = new OrganizationDto();
        BeanUtils.copyProperties(result,
                                 organization,
                                 new String[] { "parent" });
        Organization parent = organization.getParent();
        if (null != parent) {
            result.setParentId(parent.getId());
            result.setParentName(parent.getName());
        }
        return result;
    }
    
    public static Organization to(OrganizationDto dto,
                                  EntityManager entityManager) {
        Organization result = new Organization();
        if (!StringUtils.isEmpty(dto.getId())) {
            result = entityManager.find(Organization.class, dto.getId());
            
            if (null == result) {
                throw new RuntimeException("无效的建设单位id");
            }
            if (!StringUtils.isEmpty(result.getSourceSystem())) {
                throw new RuntimeException("不能修改同步自其他系统的建设单位！");
            }
        }
        result.setName(dto.getName());
        result.setCode(dto.getCode());
        result.setShortName(dto.getShortName());
        result.setDistrictCode(dto.getDistrictCode());
        result.setDistrictName(dto.getDistrictName());
        result.setLongitude(dto.getLongitude());
        result.setLatitude(dto.getLatitude());
        result.setCode(dto.getCode());
        result.setDescription(dto.getDescription());
        if (!StringUtils.isEmpty(dto.getParentId())) {
            Organization parent = entityManager.find(Organization.class,
                                                     dto.getParentId());
            result.setParent(parent);
        }
        return result;
    }
    
    private String parentId;
    
    private String parentName;
    
    public String getParentId() {
        return parentId;
    }
    
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
    
    public String getParentName() {
        return parentName;
    }
    
    public void setParentName(String parentName) {
        this.parentName = parentName;
    }
    
}
